// * 
// * ExPOUND Page Drawing
// * 
// * 
// * @copyright 2007 Loughborough University
// * @license http://www.gnu.org/licenses/gpl.txt
// * @version 0.0.0.1
// * @since Jan 2010
// * /

import classes.Layer;
import classes.Page;
import classes.layers.BlankDrawingLayerWrapper;
import classes.layers.DataModel;

import com.roguedevelopment.objecthandles.Handle;
import com.roguedevelopment.objecthandles.ObjectHandles;



import flash.events.MouseEvent;

import mx.containers.HBox;
import mx.controls.Image;
import mx.controls.Label;
import mx.controls.TextArea;
import mx.core.Application;
import mx.events.DragEvent;


//include "../mxml_views/text_tools.mxml";

public function ClearPage():void{
	//remove all the children on the main canvas display area.
	Application.application.MainCanvas.removeAllChildren()
}

public function DrawSelectedPage(CurrentPage:int):Boolean{

	drawCompulsoryComponents();
	
	//with the page number obtain an instance of the layers for the page
	
	var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[CurrentPage];
	var thisLayer:Layer = new Layer();

//check to see how many layers there are
//Alert.show(thisPage.layers.length.toString());	
	
	//loop through all of the page layers in turn and process.
	for(var eachlayer:int = 0 ; eachlayer<thisPage.layers.length; eachlayer++){
		thisLayer = thisPage.layers[eachlayer];	
	
		//get the layer type and then process as per type
		switch (thisLayer.data){
			case "Audio": 	
	    		Draw_Audio(thisLayer.label,thisLayer.obj_x_pos, thisLayer.obj_y_pos);
	        	break;
	        case "Image":							
	        	Draw_Image(thisLayer.obj_file_location, thisLayer.label, thisLayer.obj_x_pos, thisLayer.obj_y_pos);
	        	break;
	        case "Text":
	        	Draw_Text(thisLayer.label, thisLayer.obj_display_text, thisLayer.obj_x_pos, thisLayer.obj_y_pos);
	        	break;
	        case "Drawing":
	        	Draw_Drawing(thisLayer.label, thisLayer.obj_x_pos, thisLayer.obj_y_pos);
	        	break;
	        
			default:
	        	
	        	break;
	 }
	}
	
	return true;
}

private function StripStringSpaces(str:String):String{		
	var patten:RegExp = /\s+/g;
	var returnstr:String;
	
	returnstr = str.replace(patten, "");
		
	return returnstr;
}

[Bindable] protected var dataModel:DataModel;

public function Draw_Text(drawingName:String,HTMLText:String, x:int, y:int):void{
	
	
	
//	dataModel = new DataModel();
//	dataModel.x = x;
//	dataModel.y = y;
//	dataModel.height = 100;
//	dataModel.width = 100;
//	dataModel.text = HTMLText;
	
		
	var screenDisplay:TextArea = new TextArea();
	screenDisplay.id = drawingName;
	screenDisplay.htmlText = HTMLText;
	screenDisplay.enabled = false;
	screenDisplay.x = x;
	screenDisplay.y = y;
	//trial to see if by making the width and height 100% the resize into tool works
	screenDisplay.width=100;
	screenDisplay.height=100;
	
				
	var objectHandler:ObjectHandles = new ObjectHandles();
	objectHandler.allowHMove = false;
	objectHandler.allowVMove = false
	objectHandler.id = "objHandle" + drawingName;
	objectHandler.name = "objHandle" + drawingName; 
	objectHandler.addChild(screenDisplay);
	//objectHandler.registerComponent(dataModel, textArea, Handle);
	
	Application.application.MainCanvas.addChild(objectHandler);
}

public function Draw_Audio(audioName:String, x:int, y:int):void{
	          	
    var CreatedContainer:HBox = new HBox();
    CreatedContainer.id = audioName;
    CreatedContainer.x = x;
    CreatedContainer.y = y;
         	
    var btnPlay:Button = new Button();
    btnPlay.id = "btnPlay" + audioName;
    btnPlay.label = "Play";
            	     	
    CreatedContainer.addChild(btnPlay);
            	
    var btnPause:Button = new Button();
    btnPause.id = "btnPause" + audioName;
    btnPause.label ="Pause";
            	
    CreatedContainer.addChild(btnPause);
            	
    var btnStop:Button = new Button();
    btnStop.id = "btnStop" + audioName;
    btnStop.label ="Stop";
    //btnStop.setStyle("icon", "@Embed(source='../images/icons/audio/control_stop_blue.png')");
            	            	
    CreatedContainer.addChild(btnStop);
            	
    var objectHandle:ObjectHandles = new ObjectHandles();
    objectHandle.allowHMove = false;
	objectHandle.allowVMove = false
	objectHandle.id = "objHandle" + audioName;
	objectHandle.name = "objHandle" + audioName; 
    objectHandle.addChild(CreatedContainer);
            	
    //now add to the project container canvas
    Application.application.MainCanvas.addChild(objectHandle);
}

public function Draw_Image(fileLocal:String, imageName:String, x:int, y:int):void{
	
	var ProjectName:String = StripStringSpaces(Application.application._ProjectProperties._projectName.toString());
	
	var AssetFolder = "users/" + Application.application.currentUser + "/" + ProjectName + "/assets/";
//Alert.show(Application.application.serverURL + AssetFolder + fileLocal);	
	//add the layer to the container area on the screen where the user can  make modifications
	var loadedImage:Image = new Image();
	loadedImage.id = imageName;
	loadedImage.name = imageName;
	loadedImage.source = Application.application.serverURL + AssetFolder + fileLocal;
	loadedImage.x = x;
	loadedImage.y = y;
	loadedImage.percentWidth = 100;
	loadedImage.percentHeight = 100;
	//loadedImage.width = 10;
	//loadedImage.height = 10;
	
	var objectHandle:ObjectHandles = new ObjectHandles();
	objectHandle.allowRotate = false;
	objectHandle.allowHMove = false;
	objectHandle.allowVMove = false;
	objectHandle.id = "objHandle" + imageName;
	objectHandle.name = "objHandle" + imageName; 
	objectHandle.addChild(loadedImage);
	Application.application.MainCanvas.addChild(objectHandle);
}


public function Draw_Drawing(layerName:String, x:int, y:int):void{
	//create an instance of the canvas we are using
	var drawingCanvas:BlankDrawingLayerWrapper = new BlankDrawingLayerWrapper();
	drawingCanvas.id = layerName;
	drawingCanvas.width=100;
	drawingCanvas.height=100;
	drawingCanvas.x=x;
	drawingCanvas.y=y;
		
	//put a object handel wrapper around it so that we can drag and drop the tool.
	var objectHandle:ObjectHandles = new ObjectHandles();
	objectHandle.allowRotate = false;
	objectHandle.allowHMove = false;
	objectHandle.allowVMove = false
	objectHandle.id = "objHandle" + layerName;
	objectHandle.name = "objHandle" + layerName; 
	objectHandle.addChild(drawingCanvas);
	
	Application.application.MainCanvas.addChild(objectHandle);
}

public function LockDownMove():Boolean{
	
	var objName:String;
	var objectHandle:ObjectHandles;
				
    //get the current selected layer and clear the object handles for it
    for(var counter = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
		var CurrentLayerItem:XML = Application.application.layers.Layers.dataProvider.getItemAt(counter);				
		objName= "objHandle"+CurrentLayerItem.label;							
		objectHandle = Application.application.MainCanvas.getChildByName(objName);			
		objectHandle.allowHMove = false;
		objectHandle.allowVMove = false;
    } 
    return true;
}


public function AllowMove():Boolean{
	var objName:String;
	var objectHandle:ObjectHandles;

   // for(var counter:int = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
    	
    var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
//Alert.show("should have "+Application.application.currentLayerSelected);
    	
		//var CurrentLayerItem:XML = Application.application.layers.Layers.dataProvider.getItemAt(counter);				
		objName= "objHandle"+thisLayer.label;								
		objectHandle = Application.application.MainCanvas.getChildByName(objName);			
		objectHandle.allowHMove = true;
		objectHandle.allowVMove = true;

		objectHandle.addEventListener(MouseEvent.MOUSE_OUT, GrabCoordinates);
		
//Alert.show("Actually have"+objName);
	//}
    return true;
}

public function GrabCoordinates(event:MouseEvent):void{

	
	//apply the X Y coordinates to the layer information so that it can be re-drawn
	var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
	
	thisLayer.SetObjectXY(event.stageX, event.stageY);
	
	//Alert.show(Application.application._ProjectProperties.WriteXML());
	
	removeEventListener(MouseEvent.MOUSE_OUT, GrabCoordinates);
}

public function AllowResize():Boolean{
	var objName:String;
	var objectHandle:ObjectHandles;

   // for(var counter:int = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
    	
    var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
//Alert.show("should have "+Application.application.currentLayerSelected);
    	
		//var CurrentLayerItem:XML = Application.application.layers.Layers.dataProvider.getItemAt(counter);				
		objName= "objHandle"+thisLayer.label;								
		objectHandle = Application.application.MainCanvas.getChildByName(objName);
		objectHandle.allowHResize = true;
		objectHandle.allowVResize = true;

		objectHandle.addEventListener(DragEvent.DRAG_COMPLETE, resizeDone);
		
//Alert.show("Actually have"+objName);
	//}
    return true;
}

public function resizeDone(event:MouseEvent):void{

	var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
	var objName:String = "objHandle"+thisLayer.label;
	var objectHandle:ObjectHandles = Application.application.MainCanvas.getChildByName(objName);
		
		
	//get the layer type so that we can cast the object into the correct type before extracting the details we
	//need on the width and height.
	switch (thisLayer.data){
			case "Audio": 	
	//    		Draw_Audio(thisLayer.label,thisLayer.obj_x_pos, thisLayer.obj_y_pos);
		    		
	        	break;
	        case "Image":	
	        	var ImageLayer:Image = objectHandle.getChildByName(thisLayer.label.toString()) as Image;
//Alert.show(thisLayer.label.toString());	  
//Alert.show(ImageLayer.contentHeight.toString());

	        	thisLayer.obj_currentheight = ImageLayer.contentHeight;
				thisLayer.obj_currentwidth = ImageLayer.contentWidth;
	        	break;
	        case "Text":
	        	var TextLayer:TextArea = objectHandle.getChildByName(thisLayer.label.toString()) as TextArea;
	        	thisLayer.obj_currentheight = TextLayer.height;
	        	thisLayer.obj_currentwidth = TextLayer.width;
	        	break;
	        case "Drawing":
	        	var DrawingLayer:BlankDrawingLayerWrapper = objectHandle.getChildByName(thisLayer.label.toString()) as BlankDrawingLayerWrapper;
	        	thisLayer.obj_currentheight = DrawingLayer.height;
	        	thisLayer.obj_currentwidth = DrawingLayer.width;
	        	break;
		        
			default:
	        	
	        	break;
	 }
		 

//Alert.show(Application.application._ProjectProperties.WriteXML());	
	//removeEventListener(DragEvent.DRAG_COMPLETE, resizeDone);
	
}

public function AllowRotate():void{
	var objName:String;
	var objectHandle:ObjectHandles;

   // for(var counter:int = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
    	
    var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
//Alert.show("should have "+Application.application.currentLayerSelected);
    	
		//var CurrentLayerItem:XML = Application.application.layers.Layers.dataProvider.getItemAt(counter);				
		objName= "objHandle"+thisLayer.label;								
		objectHandle = Application.application.MainCanvas.getChildByName(objName);
		objectHandle.allowRotate = true;
		objectHandle.alwaysMaintainAspectRatio = false;
		
}



public function LockDown():void{
		
	var objName:String;
	var objectHandle:ObjectHandles;
				
    //get the current selected layer and clear the object handles for it
    for(var counter = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
		var CurrentLayerItem:XML = Application.application.layers.Layers.dataProvider.getItemAt(counter);				
		objName= "objHandle"+CurrentLayerItem.label;							
		objectHandle = Application.application.MainCanvas.getChildByName(objName);			
		
		//stop rotate
		objectHandle.allowRotate = false;
		
		//stop move
		objectHandle.allowHMove = false;
		objectHandle.allowVMove = false;
		
		//stop scale
		objectHandle.alwaysMaintainAspectRatio = false;
		
		
    } 
}

public function AllowScale():void{
	var objName:String;
	var objectHandle:ObjectHandles;

   // for(var counter:int = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
    	
    var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
//Alert.show("should have "+Application.application.currentLayerSelected);
    	
		//var CurrentLayerItem:XML = Application.application.layers.Layers.dataProvider.getItemAt(counter);				
		objName= "objHandle"+thisLayer.label;								
		objectHandle = Application.application.MainCanvas.getChildByName(objName);
//		objectHandle.scaleX = true;
//		objectHandle.scaleY = true;
		objectHandle.allowHResize = true;
		objectHandle.allowVResize = true;
		objectHandle.alwaysMaintainAspectRatio = true;
		
		objectHandle.addEventListener(MouseEvent.MOUSE_OUT, resizeDone);
		
}

/******************************************
 * Function to draw the components that will
 * always be displayed on screen inc uni logo
 * page numbers, home, forward navigation 
 * ****************************************/
private function drawCompulsoryComponents():Boolean{
	
	var separationValue:int = new int();
	var constGap:int = new int();
	
	constGap = 5;
	
	//add the logo at the top right of the screen and lock for editing
	var UniLogo:Image = new Image();
	UniLogo.id = "University Logo";
	UniLogo.name = "University Logo";
	UniLogo.source = Application.application.serverURL + "images/lulogo.gif";
	UniLogo.x = 570;
	UniLogo.y = 15;
		
	Application.application.MainCanvas.addChild(UniLogo);
	
	//add the next button if required
	if (Application.application._ProjectProperties._displayNextButton == true){
		var NextBtn:Image = new Image();
		NextBtn.id = "Next Button";
		NextBtn.name = "Next Button";
		NextBtn.source = Application.application.serverURL +"images/output_fixtures/next.jpg";
		NextBtn.x = 10;
		NextBtn.y = 550;
		
		separationValue = constGap + NextBtn.x + 97;
		
		Application.application.MainCanvas.addChild(NextBtn);
	}	
	
	//add the previous button
	if (Application.application._ProjectProperties._displayPreviousButton==true){
		var PreviousBtn:Image = new Image();
		PreviousBtn.id = "Next Button";
		PreviousBtn.name = "Next Button";
		PreviousBtn.source = Application.application.serverURL +"images/output_fixtures/previous.jpg";
		PreviousBtn.x = separationValue;
		PreviousBtn.y = 550;
		
		Application.application.MainCanvas.addChild(PreviousBtn);
		
		separationValue = constGap + PreviousBtn.x + 97;
	}
	
	//add the home button
	if (Application.application._ProjectProperties._displayHomeButton == true){
		var HomeBtn:Image = new Image();
		HomeBtn.id = "Home Button";
		HomeBtn.name = "Home Button";
		HomeBtn.source = Application.application.serverURL + "images/output_fixtures/home.jpg";
		HomeBtn.x = separationValue;
		HomeBtn.y = 550;
		
		Application.application.MainCanvas.addChild(HomeBtn);
		
		separationValue = constGap + HomeBtn.x + 49;
	}
	
	//add the page number buttons
	
	separationValue = separationValue + 30;
	
	if (Application.application._ProjectProperties._displayNumbers == true){
		//for the moment just have a number of numbers across the bottom at the moment 5 - 8 
		for (var i:int = 1; i<6; i++){
			var NumberButton:Image = new Image();
			NumberButton.id = "NumberBtn" + i.toString();
			NumberButton.name = "NumberBtn" + i.toString();
			var ImageFileName:String = new String();
			ImageFileName = i.toString() + ".jpg";
			NumberButton.source = Application.application.serverURL + "images/output_fixtures/" + ImageFileName;
			NumberButton.x = separationValue;
			NumberButton.y = 550;
			
			Application.application.MainCanvas.addChild(NumberButton);
			
			separationValue = separationValue + 45;
			
		}
	}
	
	//add the copyright statement
	if (Application.application._ProjectProperties._displayCopyright.length>=0){
		var CopyrightStatement:Label = new Label();
		CopyrightStatement.id = "Copyright";
		CopyrightStatement.name = "Copyright";
		CopyrightStatement.text = "Copyright " + Application.application._ProjectProperties._displayCopyright;
		CopyrightStatement.x = 570;
		CopyrightStatement.y = 575;
		
		Application.application.MainCanvas.addChild(CopyrightStatement);
	}
	
	return true;
}
